package com.yygo.webapp.controller;

import com.yygo.model.Notice;
import org.appfuse.dao.SearchException;
import org.appfuse.service.GenericManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ExtendedModelMap;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
@RequestMapping("/notices*")
public class NoticeController {
    private GenericManager<Notice, Long> noticeManager;

    @Autowired
    public void setNoticeManager(@Qualifier("noticeManager") GenericManager<Notice, Long> noticeManager) {
        this.noticeManager = noticeManager;
    }

    @RequestMapping(method = RequestMethod.GET)
    public Model handleRequest(@RequestParam(required = false, value = "q") String query)
    throws Exception {
        Model model = new ExtendedModelMap();
        try {
            model.addAttribute(noticeManager.search(query, Notice.class));
        } catch (SearchException se) {
            model.addAttribute("searchError", se.getMessage());
            model.addAttribute(noticeManager.getAll());
        }
        return model;
    }

    @RequestMapping(value = "all", method = RequestMethod.GET)
    @ResponseBody
    public List<Notice> getAllNotices(){
        return noticeManager.getAll();
    }
}
